package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.DynamicProblem;

/**
 * see 72
 *
 * @author tzp
 * @since 2020/9/16
 */
public class LC1143 implements DynamicProblem {
    public int longestCommonSubsequence(String text1, String text2) {
        if (text1 == null || text1.length() == 0 || text2 == null || text2.length() == 0) return 0;
        int[][] state = new int[text1.length()][text2.length()];
        for (int i = 0; i < text1.length(); i++) {
            for (int j = 0; j < text2.length(); j++) {
                if (i == 0 && j == 0) {
                    state[i][j] = text1.charAt(i) == text2.charAt(j) ? 1 : 0;
                    continue;
                }
                int max = Integer.MIN_VALUE;
                if (i - 1 >= 0) {
                    max = Math.max(max, state[i - 1][j]);
                }
                if (j - 1 >= 0) {
                    max = Math.max(max, state[i][j - 1]);
                }
                if (i - 1 >= 0 && j - 1 >= 0) {
                    if (text1.charAt(i) == text2.charAt(j)) {
                        max = Math.max(max, state[i - 1][j - 1] + 1);
                    }
                } else {
                    if (text1.charAt(i) == text2.charAt(j)) {
                        max = Math.max(max, 1);
                    }
                }
                state[i][j] = max;
            }
        }
        return state[text1.length() - 1][text2.length() - 1];
    }

    public static void main(String[] args) {
//        System.out.println(new LC1143().longestCommonSubsequence("abcde", "ace"));
//        System.out.println(new LC1143().longestCommonSubsequence("abcde", "ace"));
        System.out.println(new LC1143().longestCommonSubsequence("abe", "ace"));
        System.out.println(new LC1143().longestCommonSubsequence("abe", "ae"));
    }
}
